import { apiRequest, showNotification } from './utils.js';

// 评论管理模块
export class CommentModule {
  constructor() {
    this.comments = [];
    this.newComment = {
      content: '',
      author: '',
      postId: null
    };
  }

  // 加载所有评论
  async loadComments() {
    try {
      this.comments = await apiRequest('/api/comments');
      return this.comments;
    } catch (error) {
      console.error('加载评论数据失败:', error);
      throw error;
    }
  }

  // 加载特定文章的评论
  async loadPostComments(postId) {
    try {
      const comments = await apiRequest(`/api/posts/${postId}/comments`);
      return comments;
    } catch (error) {
      console.error('加载文章评论失败:', error);
      throw error;
    }
  }

  // 添加评论
  async addComment(commentData) {
    try {
      const result = await apiRequest('/api/comments', {
        method: 'POST',
        body: JSON.stringify(commentData)
      });
      
      showNotification('评论发表成功', 'success');
      return result;
    } catch (error) {
      console.error('发表评论失败:', error);
      throw error;
    }
  }

  // 更新评论
  async updateComment(commentId, content) {
    try {
      const result = await apiRequest(`/api/comments/${commentId}`, {
        method: 'PUT',
        body: JSON.stringify({ content })
      });
      
      showNotification('评论更新成功', 'success');
      return result;
    } catch (error) {
      console.error('更新评论失败:', error);
      throw error;
    }
  }

  // 删除评论
  async deleteComment(commentId) {
    try {
      await apiRequest(`/api/comments/${commentId}`, {
        method: 'DELETE'
      });
      
      showNotification('评论删除成功', 'success');
      return true;
    } catch (error) {
      console.error('删除评论失败:', error);
      throw error;
    }
  }

  // 设置评论关联的文章ID
  setPostId(postId) {
    this.newComment.postId = postId;
  }

  // 重置评论表单
  resetCommentForm() {
    this.newComment = {
      content: '',
      author: '',
      postId: this.newComment.postId
    };
  }
}